package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.bean.Category;
import com.itheima.reggie.common.R;
import com.itheima.reggie.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: 许志民
 * Date: 2021-11-24
 */
@RestController
@Slf4j
@RequestMapping("/category")
//用来描述类的信息的
//只能写在类上面
@Api(description = "瑞吉外卖分类管理API")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @ApiOperation("添加套餐分类")
    @PostMapping
    public R add(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加成功");
    }

    //    /category/page?page=1&pageSize=10
    //用来描述方法的注解
    @ApiOperation("套餐分类分页查询")
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize) {
        IPage<Category> iPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        IPage<Category> page1 = categoryService.page(iPage, lqw);
        return R.success(page1);
    }

    ///category?id=1463349706414469122 根据id删除 请求方式 DELETE
    @ApiOperation("根据id删除")
    @DeleteMapping
    public R delete(Long id) {
        if (id == null) {
            return R.error("请求失败");
        }
        boolean b = categoryService.delete(id);
        return b ? R.success("删除成功") : R.error("操作异常请重试");
    }

    //修改
    @PutMapping
    public R update(@RequestBody Category category) {
        boolean update = categoryService.updateById(category);
        return update ? R.success("修改成功") : R.error("修改失败");
    }

    @GetMapping("/list")
    public R getList(Integer type) {
        LambdaQueryWrapper<Category> wapper = new LambdaQueryWrapper<>();
        if (type != null) {
            wapper.eq(Category::getType, type);
        }
        List<Category> list = categoryService.list(wapper);
//        log.info("=++++++++++++++++++++++++++++");
        return R.success(list);
    }
}
